package com.guli.ware.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guli.ware.dto.PurchaseDemandingMergeTo;
import com.guli.common.utils.Constant;
import com.guli.ware.dao.WareSkuDao;
import com.guli.ware.entity.PurchaseDetailEntity;
import com.guli.ware.entity.WareSkuEntity;
import com.guli.ware.service.PurchaseDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;

import com.guli.ware.dao.PurchaseDao;
import com.guli.ware.entity.PurchaseEntity;
import com.guli.ware.service.PurchaseService;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDao purchaseDao;
    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuDao wareSkuDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils unreceiveList() {
        Page<PurchaseEntity> page = purchaseDao.selectPage(new Page<PurchaseEntity>(), new QueryWrapper<PurchaseEntity>()
                .eq("status", Constant.PurchaseOrderStatus.NEWCREATE.getStatus())
                .or()
                .eq("status", Constant.PurchaseOrderStatus.ALREADY_ASSIGN.getStatus()));
        return new PageUtils(page);
    }

    @Override
    public void mergePurchaseOrder(PurchaseDemandingMergeTo purchaseDemandingMergeTo) {
        Long purchaseId = purchaseDemandingMergeTo.getPurchaseId();
        if (purchaseId == null) {
            //新建一个
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(Constant.PurchaseOrderStatus.NEWCREATE.getStatus());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        Long finalPurchaseId = purchaseId;
        List<Long> items = purchaseDemandingMergeTo.getItems();
        List<PurchaseDetailEntity> purchaseDetails = items.stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(Constant.PurchaseOrderStatus.ALREADY_ASSIGN.getStatus());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(purchaseDetails);
    }

    @Override
    public void receiveOrder(Long purchaseOrderId) {
        //将领取的采购单状态设置为已领取
        PurchaseEntity purchaseOrder = this.baseMapper.selectById(purchaseOrderId);
        purchaseOrder.setStatus(Constant.PurchaseOrderStatus.HAS_CATCH.getStatus());
        this.baseMapper.updateById(purchaseOrder);
        //将与该采购单关联的所有采购需求状态设置为正在采购
        List<PurchaseDetailEntity> purchaseDetails = purchaseDetailService
                .list(new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id", purchaseOrderId));
        purchaseDetails.forEach(item -> item.setStatus(Constant.PurchaseStatus.PRUCHASING.getStatus()));
        purchaseDetailService.updateBatchById(purchaseDetails);
    }

    @Override
    public void finishOrder(Long purchaseOrderId, String isPurchase) {
        //若采购完成，将采购单状态改为已完成,将与该采购单关联的所有采购需求状态设置为已完成
        if ("true".equals(isPurchase)) {
            PurchaseEntity purchase = this.baseMapper.selectById(purchaseOrderId);
            purchase.setStatus(Constant.PurchaseOrderStatus.FINISHED.getStatus());
            this.baseMapper.updateById(purchase);
            //根据purchaseOrderId查出所有与该采购单相关联的所有采购需求
            List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseDetailService
                    .list(new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id", purchaseOrderId));
            //获取purchaseDetailEntityList所有商品Id
            purchaseDetailEntityList.forEach(purchaseDetail -> {
                //设置采购需求状态为已完成
                purchaseDetail.setStatus(Constant.PurchaseStatus.FINISHED.getStatus());
                purchaseDetailService.updateById(purchaseDetail);
                WareSkuEntity wareSku = wareSkuDao.selectOne(new QueryWrapper<WareSkuEntity>()
                        .eq("sku_id", purchaseDetail.getSkuId())
                        .eq("ware_id", purchaseDetail.getWareId()));
                //采购成功将采购商品存入库存
                if (wareSku != null) {
                    //获取原先库存中该商品库存数量
                    int stock = wareSku.getStock();
                    //设置库存数量
                    wareSku.setStock(stock + purchaseDetail.getSkuNum());
                    wareSkuDao.updateById(wareSku);
                } else {
                    //设置skuId
                    wareSku = new WareSkuEntity();
                    //设置skuId
                    wareSku.setSkuId(purchaseDetail.getSkuId());
                    //设置仓库Id
                    wareSku.setWareId(purchaseDetail.getWareId());
                    //设置库存量
                    wareSku.setStock(purchaseDetail.getSkuNum());
                    wareSkuDao.insert(wareSku);
                }
            });
        } else if ("false".equals(isPurchase)){
            //若采购失败，将采购单状态改为有异常，将与该采购单关联的所有采购需求状态设置为采购失败
            PurchaseEntity purchaseEntity = purchaseDao.selectById(purchaseOrderId);
            if (purchaseEntity == null) {
                log.debug("采购单暂不存在");
                throw new RuntimeException("采购单咱不存在");
            }
            //获取采购单编号
            Long id = purchaseEntity.getId();
            //根据采购单编号获取所有的采购单需求
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService
                    .list(new QueryWrapper<PurchaseDetailEntity>().in("purchase_id", id));
            purchaseDetailEntities.forEach(purchaseDetail -> {
                purchaseDetail.setStatus(Constant.PurchaseStatus.FAIL_PARCHASE.getStatus());
            });
            purchaseDetailService.updateBatchById(purchaseDetailEntities);
        }


    }
}